package com.yq.activemq.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class Sub1 {
    /**
     * 消息服务器地址
     */
    public static final String BROKER_URL = "tcp://localhost:61616";

    public static void main(String[] args) {
        Sub1 sub1 = new Sub1();
        sub1.receiveMessage();
    }

    private void receiveMessage() {
        Connection connection = null;
        Session session = null;
        MessageConsumer consumer = null;

        try {
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
            connection = connectionFactory.createConnection();
            session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic("myTopic");
            consumer = session.createConsumer(topic);
            connection.start();

            consumer.setMessageListener(message -> {
                try {
                    TextMessage textMessage = (TextMessage) message;
                    System.out.println(textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            });
        } catch (JMSException e) {
            e.printStackTrace();
        }

    }
}
